package com.crois.barrier.web.plugin.post;

import com.crois.barrier.common.dto.ApiRouteInfo;
import com.crois.barrier.common.enums.PluginEnum;
import com.crois.barrier.common.enums.PluginTypeEnum;
import com.crois.barrier.metrics.prometheus.register.PrometheusMetricsRegister;
import com.crois.barrier.metrics.reporter.MetricsReporter;
import com.crois.barrier.plugin.BarrierPluginChain;
import com.crois.barrier.web.cache.CacheManager;
import com.crois.barrier.web.plugin.AbstractBarrierPlugin;
import com.crois.barrier.web.support.ServerWebExchangeUtils;
import com.zhimydou.ztools.collection.CollectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Hou Ze Yu
 * @description 监控插件
 * @date 2020/5/7
 */
public class MonitorPlugin extends AbstractBarrierPlugin {

    private static final String REQUEST_TOTAL = "request_total";

    private static final String HTTP_REQUEST_TOTAL = "http_request_total";

    private CacheManager cacheManager;

    static {
        MetricsReporter.register(new PrometheusMetricsRegister());
        MetricsReporter.registerCounter(REQUEST_TOTAL, "barrier request total count");
        MetricsReporter.registerCounter(HTTP_REQUEST_TOTAL, new String[]{"path", "type"}, "barrier http request type total count");
    }

    Logger LOGGER = LoggerFactory.getLogger(MonitorPlugin.class);

    public MonitorPlugin(CacheManager cacheManager) {
        super(cacheManager);
        this.cacheManager = cacheManager;
    }

    @Override
    public PluginTypeEnum pluginType() {
        return PluginTypeEnum.POST;
    }

    @Override
    public String name() {
        return PluginEnum.MONITOR.getName();
    }

    @Override
    public int order() {
        return PluginEnum.MONITOR.getCode();
    }
    @Override
    public Boolean skip(ServerWebExchange exchange) {
        //
        ApiRouteInfo routeInfo = (ApiRouteInfo) exchange.getAttributes().get(ServerWebExchangeUtils.BARRIER_ROUTE_ATTR);
        if (CollectionUtil.isNotEmpty(routeInfo.getPlugins())){
            return !routeInfo.getPlugins().contains(PluginEnum.MONITOR.getName());
        }else {
            return true;
        }
    }

    @Override
    protected Mono<Void> doExecute(ServerWebExchange exchange, BarrierPluginChain chain, ApiRouteInfo routeInfo) {
            // 执行 监控 操作
            LOGGER.info("[开始执行：MonitorPlugin]");
            MetricsReporter.counterIncrement(REQUEST_TOTAL);
            MetricsReporter.counterIncrement(HTTP_REQUEST_TOTAL, new String[]{exchange.getRequest().getURI().getPath(), exchange.getRequest().getMethodValue()});
            LOGGER.info("[执行完成：MonitorPlugin]");
            return chain.execute(exchange);
    }

}
